package org.spruice;

import org.springframework.context.support.GenericApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class ContextBuilder {

    private final List<SpruiceModule> modules = new ArrayList<SpruiceModule>();

    public ContextBuilder register(SpruiceModule module) {
        modules.add(module);
        return this;
    }

    public ModuleContext createContext() {
        GenericApplicationContext context = new GenericApplicationContext();
        return create(context);
    }

    public ModuleContext createContext(Binder b) {
        return create(new GenericApplicationContext(), b);
    }

    public ModuleContext create(GenericApplicationContext context) {
        Binder binder = new Binder();
        return create(context, binder);
    }

    private ModuleContext create(GenericApplicationContext context, Binder binder) {
        for (SpruiceModule module : modules) {
            module.wire(binder);
        }
        for (ContextEntry builder : binder.getConfigs()) {
            builder.addTo(context);
        }
        return new ModuleContext(context);
    }
}
